package com.xjscrm.console.chat.core.impl;

import com.xjscrm.common.exception.BusinessException;
import com.xjscrm.console.chat.core.ChatBaseMsgHandler;
import com.xjscrm.console.chat.enums.ChatMsgType;
import com.xjscrm.console.chat.frame.dto.ChatRecordDTO;
import com.xjscrm.console.chat.frame.dto.ChatSessionDTO;
import com.xjscrm.console.chat.frame.recv.RPullTalkSessionMsg;
import com.xjscrm.console.chat.frame.send.SPullTalkSessionResultMsg;
import com.xjscrm.console.chat.frame.send.SResultMsg;
import com.xjscrm.console.dto.chat.ChatTalkRecordQueryDTO;
import com.xjscrm.console.entity.ChatTalkRecord;
import com.xjscrm.console.entity.ChatTalkSession;
import com.xjscrm.console.entity.ChatTalkSessionStaffRel;
import com.xjscrm.console.mapper.WwCustomerTagsMapper;
import com.xjscrm.console.mapper.WwTagsMapper;
import com.xjscrm.console.service.customer.chat.ChatTalkRecordService;
import com.xjscrm.console.service.customer.chat.ChatTalkSessionService;
import com.xjscrm.console.service.customer.chat.ChatTalkSessionStaffRelService;
import com.xjscrm.console.service.customer.wwCustomer.WwCustomerService;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author mingyang.chen create in 2024/3/12 09:41
 */
@Component
@Slf4j
public class ChatPullTalkSessionMsgHandler extends ChatBaseMsgHandler<RPullTalkSessionMsg> {

    @Autowired
    private ChatTalkSessionService chatTalkSessionService;
    @Autowired
    private ChatTalkSessionStaffRelService chatTalkSessionStaffRelService;
    @Autowired
    private ChatTalkRecordService chatTalkRecordService;
    @Autowired
    private WwCustomerService wwCustomerService;
    @Autowired
    private WwCustomerTagsMapper wwCustomerTagsMapper;
    @Autowired
    private WwTagsMapper wwTagsMapper;

    @Override
    public SResultMsg doHandle(RPullTalkSessionMsg content, ChannelHandlerContext ctx) {

        SPullTalkSessionResultMsg pullSessionResultMsg = new SPullTalkSessionResultMsg();

        Long merId = content.getMerId();
        Long staffId = content.getStaffId();
        Long deviceUniqueId = content.getDeviceUniqueId();

        try {
            // 查询机器人关联的回话
            List<ChatTalkSessionStaffRel> sessionStaffRelList;
            if (Objects.nonNull(deviceUniqueId)) {
                sessionStaffRelList = chatTalkSessionStaffRelService.listByStaffIdAndDeviceUniqueId(merId, deviceUniqueId, staffId);
            } else {
                sessionStaffRelList = chatTalkSessionStaffRelService.listByStaffId(merId, staffId);
            }
            if (ObjectUtils.isEmpty(sessionStaffRelList)) {
                return pullSessionResultMsg;
            }

            List<ChatSessionDTO> sessionMsgs = new ArrayList<>(sessionStaffRelList.size());

            for (ChatTalkSessionStaffRel sessionStaffRel : sessionStaffRelList) {
                //
                ChatTalkSession talkSession = chatTalkSessionService.getById(merId, sessionStaffRel.getTalkSessionId());
                if (Objects.nonNull(talkSession) && Objects.equals(talkSession.getOpenShield(), 1)) {
                    continue;
                }
                Integer lastReadTime = talkSession.getLastReadTime();
                Integer noReadCount;
                if (Objects.isNull(lastReadTime)) {
                    noReadCount = chatTalkRecordService.countWithNoRead(merId, sessionStaffRel.getTalkSessionId(), null);
                } else {
                    noReadCount = chatTalkRecordService.countWithNoRead(merId, sessionStaffRel.getTalkSessionId(), lastReadTime);
                }

                ChatSessionDTO talkSessionMsg = chatTalkSessionService.convert(talkSession);

                talkSessionMsg.setOpenPinTop(sessionStaffRel.getOpenPinTop());
                talkSessionMsg.setOpenPinTopTime(sessionStaffRel.getOpenPinTopTime());
                talkSessionMsg.setOpenSilence(sessionStaffRel.getOpenSilence());
                talkSessionMsg.setOpenSilenceTime(sessionStaffRel.getOpenSilenceTime());
                talkSessionMsg.setExpire(sessionStaffRel.getExpire());
                talkSessionMsg.setExpireTime(sessionStaffRel.getExpireTime());
                talkSessionMsg.setShowExpireTime(sessionStaffRel.getShowExpireTime());
                talkSessionMsg.setEnd(sessionStaffRel.getEnd());
                talkSessionMsg.setEndTime(sessionStaffRel.getEndTime());

//                chatTalkSessionService.fillTag(talkSession, tag -> {
//                    if (Objects.equals(tag.getType(), 1)) {
//                        talkSessionMsg.getCompanyTagIds().add(tag.getId());
//                    } else if (Objects.equals(tag.getType(), 1)) {
//                        talkSessionMsg.getSelfTagIds().add(tag.getId());
//                    }
//                }, tag1 -> {
//                    talkSessionMsg.getSelfTagIds().add(tag1.getId());
//                });
//
//                chatTalkSessionService.fillConversationName(talkSession, talkSessionMsg);

                talkSessionMsg.setNoReadCount(noReadCount);
                talkSessionMsg.setLastReadTime(lastReadTime);
                talkSessionMsg.setLastTalkRecord(this.doLoadTalkRecord(merId, talkSession.getLastRecvId()));
                talkSessionMsg.setExpire(sessionStaffRel.getExpire());
                talkSessionMsg.setExpireTime(sessionStaffRel.getExpireTime());
                talkSessionMsg.setShowExpireTime(sessionStaffRel.getShowExpireTime());
                talkSessionMsg.setShowExpireTime(sessionStaffRel.getShowExpireTime());
                sessionMsgs.add(talkSessionMsg);
            }

            pullSessionResultMsg.setSessions(sessionMsgs);
        } catch (Exception e) {
            log.error("拉取机器人回话失败", e);
            throw new BusinessException("拉取机器人回话失败");
        }
        return pullSessionResultMsg;
    }

    @Override
    public Class<RPullTalkSessionMsg> msgClass() {
        return RPullTalkSessionMsg.class;
    }

    @Override
    public ChatMsgType msgType() {
        return ChatMsgType.r_pull_session;
    }

    private ChatRecordDTO doLoadTalkRecord(Long merId, Long lastTalkId) {
        ChatTalkRecordQueryDTO chatTalkRecordQuery = new ChatTalkRecordQueryDTO();
        chatTalkRecordQuery.setId(lastTalkId);
        chatTalkRecordQuery.setMerId(merId);
        ChatTalkRecord chatTalkRecord = chatTalkRecordService.loadLastTalk(chatTalkRecordQuery);
        if (Objects.isNull(chatTalkRecord)) {
            return null;
        }
        ChatRecordDTO chatRecordDTO = new ChatRecordDTO();
        BeanUtils.copyProperties(chatTalkRecord, chatRecordDTO);
        chatRecordDTO.parse();
        return chatRecordDTO;
    }
}
